//
//  PasteRecord.swift
//  HisPaste
//
//  Created by 烟雀 on 2024/2/16.
//

import Foundation

class ObervableMaxArray: MaxArray, ObservableObject{
    
    // static let this = ObervableMaxArray()
    
    @Published
    var inCache_: [String] = []
    
    override internal var _cache: [String]{
        get {self.inCache_}
        set {self.inCache_ = newValue}
    }
    
}

class PasteRecord: ObservableObject{
    
    // 单例
    static let this = PasteRecord()
    
    @Published
    var records: ObervableMaxArray = ObervableMaxArray()
    
    let cacheToDisk = CacheDisk()
    
    // 单例
    private init() {
        self.loadFromDisk()
        SystemPaste.didChangePasteEvent(self.updateFromSystemPaste)
        SystemPaste.checkPasteChange()
    }
    
    private func loadFromDisk(){
        if let jsonData = self.cacheToDisk.loadFromCache(){
            if let diskRecords = jsonData["diskData"]{
                self.records.load(diskRecords)
            }
        }
    }
    
    private func cache(){
        self.cacheToDisk.writeToCache(data: ["diskData": self.records.getAll()])
    }
    
    private func updateFromSystemPaste(curPasteStr: String?){
        if (curPasteStr != nil){
            AppLog.debug("事件获取到剪贴板变化" + curPasteStr!)
            // 如果存在, 就移除并提到第一个
            // self.clearPasteItem(curPasteStr)
            // curPasteStr!.replacingOccurrences(of: " ", with: " ")
            if self.checkSpecStr(curPasteStr!) {return}
            self.records.insertWithRm(curPasteStr, at: 0)
            self.cache()
        } else {
            AppLog.debug("事件获取到剪贴板变化, no val")
        }
    }
    
    private func checkSpecStr(_ data: String) -> Bool{
        let spcStr = " "
        if data.contains(spcStr){
            SystemPaste.writeToPaste(data: data.replacingOccurrences(of: " ", with: " ", options: .literal))
            return true
        }
        return false
    }
    
    func clearPasteItem(_ data: String?){
        let _ = self.records.removeItem(data)
    }
    
}

